<?php
	// $this->start('css');
 //        echo $this->Html->css('jquery-ui/jquery-ui-1.10.3.custom.min');
 //        //echo $this->Html->css('Index/index');        
 //        echo $this->Html->css('jquery.ui.timepicker');
 //    $this->end();
 //    $this->start('script');
	// 	echo $this->Html->script("jquery-1.10.2.min");
 //        echo $this->Html->script("jquery-ui-1.10.3.custom.min");
 //        echo $this->Html->script(array(
 //            "jquery.dataTables.min", 
 //            "jquery.ui.timepicker.min", 
 //            ));
 //        //echo $this->Html->script("http://js.cit.api.here.com/se/2.5.3/jsl.js?with=all");        
	// 	//echo $this->Html->script("prediccion_mapas");	
 //    $this->end();
    $this->assign('title', "Extraer Coordenadas - miBus");
	
	$base_url = $this->Html->url('/');
?>
<table align="center">
	<tr>
		<td>Ruta:</td>
		<td>
			<select id="id_ruta_id" name="ruta_id">										
				<?php				
					foreach ($todas_rutas as $key => $registro){
						$values = $registro['Ruta'];
						
						if ($id_ruta == $values["id_ruta"]){
							echo "<option value=\"".$values["id_ruta"]."\" selected>(".$values["id_ruta"].") - ".$values["nombre_ruta"]."</option>";
						} else {
							echo "<option value=\"".$values["id_ruta"]."\">(".$values["id_ruta"].") - ".$values["nombre_ruta"]."</option>";
						}
					}
				?>
			</select>
		</td>
		<td>
			<input type="button" name="extraer" value="Extraer" onclick="extraer_coordenadas();">
		</td>
		<td>
			<input type="button" id="id_botton_guardar" name="guardar" value="Guardar" onclick="guardar_coordenadas();" style="display: none;">
		</td>
	</tr>
</table>
<table align="center">
	<tr>
		<td>
			<textarea id="id_route_coords" name="route_coords" cols="40" rows="25" style="font-size: 8pt;"></textarea>
		</td>
		<td>
			<div id="mapContainer" style="height: 500px; width: 1050px;"></div>					
		</td>
	</tr>	
</table>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.4/jsl.js?with=all"></script>
<script type="text/javascript" charset="UTF-8" src="<?php echo $base_url; ?>js/prediccion_mapas.js"></script>
<script type="text/javascript" id="funciones_extraccion">	

	//Inicializar mapas...
	iniciar_mapas();

	var markersContainer = {
		rutas: new nokia.maps.map.Container(), 
		paradas: new nokia.maps.map.Container(),
	};
		
	var icon_parada = new nokia.maps.gfx.BitmapImage("<?php echo $base_url; ?>img/parada_3.png", null, 30, 30, 0, 0);

	//Data sobre la ruta....
	var current_waypoints_ayuda = [];
	var current_paradas = [];
	var ultima_ruta_id = null;
	var route_latlong;
		
	function extraer_coordenadas(){		
		
		var id_ruta = document.getElementById('id_ruta_id').value;
		ultima_ruta_id = id_ruta;
<?php
	$coords_url = $this->Html->url(array("controller" => "Predicciones", "action" => "obtener_paradas_ruta", "ext" => "json"));
?>				
		$.get("<?php echo $coords_url; ?>?id_ruta=" + id_ruta, coordenadas_recuperadas);
	}			
	
	function guardar_coordenadas(){
		document.getElementById("id_botton_guardar").disabled = true;
<?php
	$guardar_url = $this->Html->url(array("controller" => "Predicciones", "action" => "guardar_coordenadas", "ext" => "json"));
?>
		$.post("<?php echo $guardar_url; ?>", {ruta_id: ultima_ruta_id, coord_str: route_latlong})
			.done(function(data){
				if (data.resultado == "1"){
					alert("Coordenadas guardadas exitosamente");
				} else {
					alert("Hubo un error al guardar coordenadas");
				}				
				document.getElementById("id_botton_guardar").disabled = false;
			});
	}
	
	
	//Funcion que grafica la ruta una vez que se ha calculado....
	var onRouteCalculated = function (observedRouter, key, value) {
		
		if (value == "finished") {
			var routes = observedRouter.getRoutes(),
				route = routes[0],
				waypoints = route.waypoints,
				i, length = waypoints.length;
			
			var lineColor = "#285999";
			
			var linea_ruta = new nokia.maps.map.Polyline(route.shape, {
				pen : new nokia.maps.util.Pen({
					lineWidth: 5, 
					strokeColor: lineColor
				}),
				arrows: new nokia.maps.util.Arrows({
					color: "#FFFFFF"
				})
			});
			
			linea_ruta.set("id_ruta", observedRouter.get("id_ruta"));
			linea_ruta.addListener("mouseover" ,  function(evt) { 
				evt.target.set("pen", new nokia.maps.util.Pen({
					lineWidth: 5, 
					strokeColor: "#F54046"
				}));
				evt.target.set("zIndex", 100);
				map.update(-1, 0);
			});
			linea_ruta.addListener("mouseout" ,  function(evt) {
				evt.target.set("pen", new nokia.maps.util.Pen({
					lineWidth: 5, 
					strokeColor: lineColor
				}));
				evt.target.set("zIndex", 2);
				map.update(-1, 0);
			});
			
			//Agregar la ruta al mapa, quitando la anterior
			map.objects.remove(markersContainer.rutas);
			markersContainer.rutas.objects.clear();
			markersContainer.rutas.objects.add(linea_ruta);
			map.objects.add(markersContainer.rutas);
			
			//Dibujar las paradas
			var waypoints_ayuda_positions = observedRouter.get("waypoints_ayuda_positions");
			var paradas_waypoints = observedRouter.get("paradas_waypoints");
			map.objects.remove(markersContainer.paradas);
			markersContainer.paradas.objects.clear();
			for (i = 0; i < length; i++) {
				if (waypoints_ayuda_positions.indexOf(i) != -1) {
					continue;
				}

				var markerParada = new nokia.maps.map.Marker(waypoints[i].originalPosition, {
					icon: icon_parada,
					anchor: new nokia.maps.util.Point(15, 15)
				});
				markerParada.parada = paradas_waypoints[i];
				
				markersContainer.paradas.objects.add(markerParada);
			}
			map.objects.add(markersContainer.paradas);
			
			var n_coords = route.shape.getLength();
			var latlong = String(route.shape.getLatLng(0, n_coords));
			route_latlong = latlong;					
			
			var route_shape_parts = latlong.split(",");
			var coords_text = "";
			for (var j = 0; j < n_coords; j++){
				coords_text += route_shape_parts[j * 2] + "\t" + route_shape_parts[j * 2 + 1] + "\n";
			}
			document.getElementById('id_route_coords').innerHTML = coords_text;
			
			document.getElementById("id_botton_guardar").style.display = "";						
			
		} else if (value == "failed") {
			alert("Fallo en enrutamiento!");
			ultima_ruta_id = null;
		}	
	};

</script>
